package com.example.commuinte_backed.controller;

import com.example.commuinte_backed.common.api.ApiResult;
import com.example.commuinte_backed.model.dto.CommentDTO;
import com.example.commuinte_backed.model.entity.BmsComment;
import com.example.commuinte_backed.model.entity.UmsUser;
import com.example.commuinte_backed.model.vo.CommentVO;
import com.example.commuinte_backed.service.IBmsCommentService;
import com.example.commuinte_backed.service.IBmsPostService;
import com.example.commuinte_backed.service.IUmsUserService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import static com.example.commuinte_backed.jwt.JwtUtil.USER_NAME;


@RestController
@RequestMapping("/comment")
public class BmsCommentController extends BaseController {

    @Resource
    private IBmsCommentService bmsCommentService;
    @Resource
    private IUmsUserService umsUserService;
    @Resource
    private IBmsPostService bmsPostService;

    @Resource
    private IBmsCommentService iBmsCommentService;
    @GetMapping("/get_comments")
    public ApiResult<List<CommentVO>> getCommentsByTopicID(@RequestParam(value = "topicid", defaultValue = "1") String topicid) {
        List<CommentVO> lstBmsComment = bmsCommentService.getCommentsByTopicID(topicid);
        return ApiResult.success(lstBmsComment);
    }
    @PostMapping("/add_comment")
    public ApiResult<BmsComment> add_comment(@RequestHeader(value = USER_NAME) String userName,
                                             @RequestBody CommentDTO dto) {
        UmsUser user = umsUserService.getUserByUsername(userName);
        bmsPostService.addComment(dto.getTopic_id());
        BmsComment comment = bmsCommentService.create(dto, user);
        return ApiResult.success(comment);
    }

    @DeleteMapping("/delete_comment/{id}")
    public ApiResult<String>delete_comment(@RequestHeader(value = USER_NAME) String userName,
                                           @PathVariable("id") String id){

        UmsUser user = umsUserService.getUserByUsername(userName);

        BmsComment bmsComment=bmsCommentService.getById(id);

        Assert.notNull(bmsComment, "来晚一步，评论已不存在");
        Assert.isTrue(bmsComment.getUserId().equals(user.getId()), "你为什么可以删除别人的话题？？？");
        bmsPostService.deleteComment(bmsComment.getTopicId());
        ;
        iBmsCommentService.removeById(id);

        return ApiResult.success(null,"删除成功");

    }

}